const fs = require('fs');
const path = require('path');
const {
	question,
} = require('./utils/realline.js');
const log = (...args) => {
	console.log('-------------------\n');
	const len = args.length;
	args.forEach((str,idx) => {
		console.log(str);
	})
	console.log('\n');
};

const params = process.argv.splice(2);
const argvs = {
	keyword:params[0]||'',
	path:params[1]||'',
	findAll:params[2] ? Number(params[2]) || 1 : 1,
}
// log('argvs --->\n',argvs);
const onSearch = async () => {
	let startPath = argvs.path;
	if(!startPath){
		return false;
		startPath = path.resolve(__dirname, await question('请输入开始查找路径'));
	}
	let keyword = argvs.keyword;
	if(!keyword){
		return false;
		keyword = await question('请输入开始查找关键字');
	}
	keyword = keyword.trim();
	// log('r --->\n',{keyword,startPath});
	const findFiles = _findFile(startPath,keyword,{
		findAll:argvs.findAll === 1,
	});
	if(findFiles.length > 0){
		log('找到以下文件 --->\n',findFiles.join('\n'));
	}else{
		log(`未找到与【${keyword}】相关的文件`)
	}
}
const _findFile = (searchPath,subFileName="",opts = {}) => {
	opts = {
		// 遍历所有子目录
		findAll:true,
		...opts
	}
	const files = fs.readdirSync(searchPath);
	let folders = [], findFiles = [];
	files.forEach(function (fileName, index) {
	    let fPath = path.join(searchPath,fileName);
	    let stat = fs.statSync(fPath);
	    if(stat.isDirectory() === true) {
	    	if(opts.findAll){
	    		findFiles = findFiles.concat(_findFile(fPath,subFileName,opts));
	    	}else{
	    		folders.push(fPath);
	    	}
	    }else if (stat.isFile() === true && fileName.indexOf(subFileName) !== -1) {
	      findFiles.push(fPath);
	    }
	});
	if(!opts.findAll && folders.length > 0){
		log('有以下子文件夹\n',folders)
	}
	return findFiles;
}
onSearch();

